from localtime import sync_net_time

def do_connect():
    import network
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('TPGuest_hanxiaoxin', '114114114')
        while not wlan.isconnected():
            pass
    print('network config:', wlan.ifconfig())
    
def upload_data(data):
    import socket
    addr = socket.getaddrinfo('creation-hardware.codemao.cn', 3000)[0][-1]
    s = socket.socket()
    s.connect(addr)
    s.send(data)
    data = s.recv(1000)
    print(data)
    s.close()
    return data
    
def to_json(data_dict = {}):
    json_prefix = "{"
    json_suffix = "}"
    json_content = ""
    length = len(data_dict)
    count = 0

    for key in data_dict:
        count += 1
        k = '"' + key + '"'
        v = '"' + str(data_dict[key]) + '"'
        s = ":"
        unit = k + s + v
        if count < length:
            unit += ","
        json_content += unit
    return json_prefix + json_content + json_suffix
        
def upload_codemao(data_str = ''):
    try:
        do_connect()
        payload = {
            "op": "upload",
            "topic": "Tiot_StS2EuHr",
            "name": "dataset",
            "data": data_str
        }
        upload_data(to_json(payload))
    except Exception as e:
        print(e)
        
def getTime():
    try:
        do_connect()
        payload = {
            "op": "query",
            "topic": "Tiot_StS2EuHr",
            "name": "time",
        }
        resp = upload_data(to_json(payload))
        sync_net_time(str(resp))
    except Exception as e:
        print(e)

